package gui.swing;

import javax.swing.*;
import java.awt.*;

/**
 * javax.swing.ImageIcon
 *
 * 常用构造方法
 * ImageIcon(Image image)
 * ImageIcon(String name)
 * ImageIcon(URL url)
 *
 * 主要方法
 * int getIconHeight()      获取图片高度
 * int getIconWidth()       获取图片宽度
 * void paintIcon(Component c,Graphics g,int x,int y)
 *
 *
 *
 *
 * 加载图像的几个步骤
 *
 * 第一步：在程序开头导入图像类
 * import java.awt.Image； //AWT组件方式
 * import javax.swing.ImageIcon；//SWING组件方式
 *
 * 第二步：获取要显示的图像，利用getToolkit()方法获取工具包Toolkit引用，再利用Toolkit的getImage方法装载图像
 * Image getImage (URL url, String name );  // 方法可接受 String 或者是 URL 参数，用以指定图像文件的路径
 *                                          // 在Applet类里也有getImage方法
 * 第三步：显示加载的图象
 * 在获得图像后，利用Graphics类提供的drawImage这个方法把Image对象在程序里绘制出来
 * */
public class ImageIconDemo {
    // 静态变量存在方法区中
    public static ImageIcon battleship;
    public static ImageIcon mainSubmarine;
    public static ImageIcon observerSubmarine;
    public static ImageIcon torpedoSubmarine;
    public static ImageIcon bomb;
    public static ImageIcon mine;
    public static ImageIcon sea;
    public static ImageIcon gameOver;

    static {    // 静态块，在类加载时执行并且只执行一次，存在方法区中
        battleship = new ImageIcon("img/SubmarineWar/battleship.png");
        mainSubmarine = new ImageIcon("img/SubmarineWar/minesubm.png");
        observerSubmarine = new ImageIcon("img/SubmarineWar/obsersubm.png");
        torpedoSubmarine = new ImageIcon("img/SubmarineWar/torpesubm.png");
        bomb = new ImageIcon("img/SubmarineWar/bomb.png");
        mine = new ImageIcon("img/SubmarineWar/mine.png");
        sea = new ImageIcon("img/SubmarineWar/sea.png");
        gameOver = new ImageIcon("img/SubmarineWar/gameover.png");
    }

    public static void main(String[] args) {
        JFrame jFrame = new JFrame("图片测试");
        MyPanel myPanel = new MyPanel();
        jFrame.add(myPanel);
        jFrame.pack();
        jFrame.validate();
        jFrame.setVisible(true);
        int state = sea.getImageLoadStatus();   // 获取图片加载状态，返回8则加载成功，返回其他值则加载失败
        System.out.println(state);
    }
}

class MyPanel extends JPanel
{
    private JButton jb1 = null;
    private JButton jb2 = null;
    private Image image = getToolkit().getImage("img/SubmarineWar/battleship.png");
    private ImageIcon imageIcon = new ImageIcon("img/SubmarineWar/battleship.png");

    public MyPanel()
    {
        super();
        jb1 = new JButton();
        image = image.getScaledInstance(50,50,image.SCALE_DEFAULT);
        jb1.setIcon(new ImageIcon(image));
        jb2 = new JButton(imageIcon);
        this.add(jb1);
        this.add(jb2);
    }
}
